<template>
    <div ref="chartContainers" class="chart-container"></div>
</template>

<script setup lang="ts">
import { onMounted, ref, watch } from 'vue';
import * as echarts from 'echarts/core';
import titleIcon from '@/assets/images/titleIcon.png';
import {
    CanvasRenderer
} from 'echarts/renderers';
import {
    PieChart
} from 'echarts/charts';
import {
    TitleComponent,
    TooltipComponent,
    LegendComponent,
    GridComponent
} from 'echarts/components';
import { use } from 'echarts/core';

// 导入所需组件
use([
    CanvasRenderer,
    PieChart,
    TitleComponent,
    TooltipComponent,
    LegendComponent,
    GridComponent
]);
const props = defineProps({
    data: {
        type: Array,
        default: () => []
    },
    title: {
        type: String,
        default: '地震频率'
    },
})

const chartContainers = ref(null);
const chartInstances = ref(null);
// 动态生成渐变色
function getGradientColor(index: number): echarts.graphic.LinearGradient {
  let startColor: string;
  let endColor: string;

  switch (index) {
    case 0:
      startColor = '#55B68B';
      endColor = '#4EA775';
      break;
    case 1:
      startColor = '#3560F6';
      endColor = '#69D0FF';
      break;
    case 2:
      startColor = '#FA880E';
      endColor = '#F4BA43';
      break;
  }

  return new echarts.graphic.LinearGradient(
    0, 0, 0, 1, // 渐变方向，从上到下
    [
      { offset: 0, color: startColor }, // 起始颜色
      { offset: 1, color: endColor }  // 结束颜色
    ]
  );
}
// 自定义 label 的 formatter 函数
function labelFormatter(params: echarts.EChartsLabelFormatterParams) {
  const name = params.name;
  const value = params.value;
  const gradientColor = getGradientColor(params.dataIndex);
  // 使用 CSS 渐变背景和 -webkit-background-clip: text; 实现文本渐变色
  return `
    <div>
      <div>${name}级:</div>
      <div class="gradient-text" style="background: ${gradientColor}; -webkit-background-clip: text; color: transparent;">
        共${value}次
      </div>
    </div>
  `;
}
const initChart = () => {
    chartInstances.value = echarts.init(chartContainers.value);
    props.data.map(item=>{
        item.value = item.totalCount;
        item.name = item.magnitudeRange
    })
    const concentricCircleOptions = {
        title: {
            text:  `{icon|}{text|地震频次}` ,
            textStyle: {
                rich: {
                    icon: {
                        backgroundColor: {
                            image: titleIcon
                        },
                        width: 16,
                        height: 16,
                        align: 'center',
                        verticalAlign: 'middle',
                    },
                    text: {
                        color: '#333',
                        fontSize: 16,
                        align: 'left',
                        verticalAlign: 'middle',
                        padding:[4, 0, 0, 4]
                    }
                }
            },
            left: 'left',
            top: 'top'
        },
        tooltip: {
            trigger: 'item',
            formatter: function (params) {
                // 自定义标签的内容
                return `${params.name}级: \n共${params.value}次`;
            }
        },
        legend: {
            data:  props.data.map((dataset, index) => ({
              name: dataset.name,
              textStyle: {
                color: '#333333' // 默认黑色文字
              },
              itemStyle: {
                color: getGradientColor(index, 0), // 图例颜色
                borderRadius: [5,5,5,5]
              },
              itemWidth: 10,  // 图例标记的图形宽度
              itemHeight: 10, // 图例标记的图形高度
              icon: 'roundRect',
              symbolSize: 10,
            })),
            right: '2%',
        },
        series: [
            {
                name: props.title,
                type: 'pie',
                radius: ['45%', '65%'],
                avoidLabelOverlap: false,
                emphasis: {
                    label: {
                        show: true,
                        fontSize: '20',
                        fontWeight: 'bold'
                    }
                },
                data: props.data.map((dataset, index) => ({
                  name: dataset.name,
                  value: dataset.value,
                  itemStyle: {
                    color: getGradientColor(index) // 设置渐变色
                  }
                })),
                label: {
                    show: true,
                    position: 'outside',
                    formatter: function (params) {
                        // 自定义标签的内容
                        return `${params.name}级: \n共${params.value}次`;
                    },
                }
            }
        ]
    };

    chartInstances.value.setOption(concentricCircleOptions);
};

const resizeChart = () => {
    if (chartInstances.value) {
        chartInstances.value.resize();
    }
};

watch(() => props.data, () => { 
    initChart();
}, { deep: true });

onMounted(() => {
    initChart();
    window.addEventListener('resize', resizeChart);
});

onUnmounted(() => {
    window.removeEventListener('resize', resizeChart);
});
</script>

<style scoped>
.chart-container {
    width: 100%;
    height: 400px;
}
</style>